import { Base64 } from 'js-base64';

export const utilEncoding = (params) => {
  let formatParams = typeof(params) === "string" ? params : JSON.stringify(params);
  return Base64.encode(utilEncodingURL(formatParams));
}

export const utilDecoding = (params) => {
  return params ? JSON.parse(utilDecodingURL(Base64.decode(params))) : null;
}

export const utilEncodingURL = (params) => {
  return encodeURIComponent(JSON.stringify(params));
}

export const utilDecodingURL = (params) => {
  let result;
  try {
    result = decodeURIComponent(params);
  } catch (error) {
    result = JSON.stringify("{}");
  }
  return result;
}

export const utilFormateDate = (params) => {
  // 判断返回的数据是否是时间戳
  if (!!!params) { 
    return 
  }
  if (params.indexOf("-") === -1) {
    let date = new Date( parseInt(params) * 1000 );
    let Y = date.getFullYear() + '-'; // 年
    let M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-'; // 月
    let D = date.getDate() + ' '; // 日
    return Y + M + D;
  }else {
    return params;
  }
}

// 判断当前运行的环境 1-qq 2-微信
export const utilClient = () => {
  if (!window) {
    return -1;
  }
  let ua = navigator.userAgent.toLowerCase();
  if (ua.indexOf('qq/') !== -1) {
    return 1;
  }else if(ua.match(/MicroMessenger/i) == 'micromessenger') {
    return 2;
  }else {
    return 0;
  }
}